package com.leo.erp.web.supplier;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.leo.erp.dto.SupplierExecution;
import com.leo.erp.dto.UserBusinessExecution;
import com.leo.erp.entity.Supplier;
import com.leo.erp.enums.SupplierStateEnum;
import com.leo.erp.enums.UserBusinessStateEnum;
import com.leo.erp.service.SupplierService;
import com.leo.erp.service.SystemConfigService;
import com.leo.erp.service.UserBusinessService;
import com.leo.erp.util.ExcelUtils;
import com.leo.erp.util.ExportExecUtil;
import com.leo.erp.util.GlobalRuntimeException;
import com.leo.erp.util.HttpServletRequestUtil;

import jxl.Sheet;
import jxl.Workbook;

@Controller
@RequestMapping(value = "/supplier")
public class SupplierManagementController {
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private UserBusinessService userBusinessService;
	@Autowired
	private SystemConfigService systemConfigService; 
	
	/**
	 * 导入excel表格-供应商
	 * @param supplierFile
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	@RequestMapping(value = "/importExcelVendor")
	@ResponseBody
	public void importExcelVendor(MultipartFile supplierFile, HttpServletRequest request, HttpServletResponse response) throws IOException {
		importFun(supplierFile);
        response.sendRedirect("../page/vendor");
	}
	
	private void importFun(MultipartFile supplierFile) {
		Map<String, Object> modelMap = new HashMap<>();
		try {
			Sheet src = null;
			//文件合法性校验
			try {
				Workbook workbook = Workbook.getWorkbook(supplierFile.getInputStream());
				src = workbook.getSheet(0);
			} catch (Exception e) {
				modelMap.put("success", false);
				modelMap.put("msg", "导入文件不合法，请检查");
			}
			//每行中数据顺序 "名称","类型","联系人","电话","电子邮箱","预收款","期初应收","期初应付","备注","传真","手机","地址","纳税人识别号","开户行","账号","税率","状态"
            List<Supplier> sList = new ArrayList<Supplier>();
            for (int i = 1; i < src.getRows(); i++) {
                Supplier s = new Supplier();
                s.setSupplier(ExcelUtils.getContent(src, i, 0));
                s.setType(ExcelUtils.getContent(src, i, 1));
                s.setContacts(ExcelUtils.getContent(src, i, 2));
                s.setPhoneNum(ExcelUtils.getContent(src, i, 3));
                s.setEmail(ExcelUtils.getContent(src, i, 4));
                s.setAdvanceIn(Double.parseDouble(ExcelUtils.getContent(src, i, 5)));
                s.setBeginNeedGet(Double.parseDouble(ExcelUtils.getContent(src, i, 6)));
                s.setBeginNeedPay(Double.parseDouble(ExcelUtils.getContent(src, i, 7)));
                s.setDescription(ExcelUtils.getContent(src, i, 8));
                s.setFax(ExcelUtils.getContent(src, i, 9));
                s.setTelephone(ExcelUtils.getContent(src, i, 10));
                s.setAddress(ExcelUtils.getContent(src, i, 11));
                s.setTaxNum(ExcelUtils.getContent(src, i, 12));
                s.setBankName(ExcelUtils.getContent(src, i, 13));
                s.setAccountNumber(ExcelUtils.getContent(src, i, 14));
                s.setTaxRate(Double.parseDouble(ExcelUtils.getContent(src, i, 15)));
                String enabled = ExcelUtils.getContent(src, i, 16);
                s.setEnabled(enabled.equals("启用")? 1 : 0);
                s.setIsSystem(Byte.parseByte("1"));
                sList.add(s);
            }
            SupplierExecution se = supplierService.importExcel(sList);
            if(se.getState() == SupplierStateEnum.SUCCESS.getState()) {
            	modelMap.put("success", true);
            }else {
            	modelMap.put("success", false);
            	modelMap.put("msg", "导入失败");
            }
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}

	/**
	 * 生成excel表格
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/exportExcel")
	@ResponseBody
	public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
		//获取前台传过来的值
		String supplier = HttpServletRequestUtil.getString(request, "supplier");
		String type = HttpServletRequestUtil.getString(request, "type");
		String phoneNum = HttpServletRequestUtil.getString(request, "phonenum");
		String telephone = HttpServletRequestUtil.getString(request, "telephone");
		String description = HttpServletRequestUtil.getString(request, "description");
		
		try {
			List<Supplier> dataList = supplierService.findByAll(supplier, type, phoneNum, telephone, description);
			String[] names = {"名称", "类型", "联系人", "电话", "电子邮箱", "预收款", "期初应收", "期初应付", "备注", "传真", "手机", "地址", "纳税人识别号", "开户行", "账号", "税率", "状态"};
            String title = "信息报表";
            List<String[]> objects = new ArrayList<String[]>();
            if (null != dataList) {
                for (Supplier s : dataList) {
                    String[] objs = new String[17];
                    objs[0] = s.getSupplier();
                    objs[1] = s.getType();
                    objs[2] = s.getContacts();
                    objs[3] = s.getPhoneNum();
                    objs[4] = s.getEmail();
                    objs[5] = s.getAdvanceIn() == 0 ? "0" : String.valueOf(s.getAdvanceIn());
                    objs[6] = s.getBeginNeedGet() == 0 ? "0" : String.valueOf(s.getBeginNeedGet());
                    objs[7] = s.getBeginNeedPay() == 0 ? "0" : String.valueOf(s.getBeginNeedPay());
                    objs[8] = s.getDescription();
                    objs[9] = s.getFax();
                    objs[10] = s.getTelephone();
                    objs[11] = s.getAddress();
                    objs[12] = s.getTaxNum();
                    objs[13] = s.getBankName();
                    objs[14] = s.getAccountNumber();
                    objs[15] = s.getTaxRate() == 0 ? "0" : String.valueOf(s.getTaxRate());
                    objs[16] = s.getEnabled() == 1 ? "启用" : "禁用";
                    objects.add(objs);
                }
            }
            File file = ExcelUtils.exportObjectsWithoutTitle(title, names, title, objects);
            ExportExecUtil.showExec(file, file.getName(), response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 批量设置状态-启用或者禁用
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/batchSetEnable")
	@ResponseBody
	public Map<String, Object> batchSetEnable(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		int enabled = HttpServletRequestUtil.getInt(request, "enabled");
		String supplierIDs = HttpServletRequestUtil.getString(request, "supplierIDs");
		
		SupplierExecution se = supplierService.batchSetEnable(enabled, supplierIDs);
		if(se.getState() == SupplierStateEnum.SUCCESS.getState()) {
			modelMap.put("success", true);
		}else {
			modelMap.put("success", false);
			modelMap.put("msg", "服务内部错误");
		}
		
		return modelMap;
	}
	
	/**
	 * 批量删除供应商信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/batchDeleteSupplierByIds")
	@ResponseBody
	public Map<String, Object> batchDeleteSupplierByIds(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		String ids = HttpServletRequestUtil.getString(request, "ids");
		String deleteType = HttpServletRequestUtil.getString(request, "deleteType");//1:正常删除,2:强制删除
		SupplierExecution se = new SupplierExecution();
		if("1".equals(deleteType)) {
			//正常删除
			se = supplierService.batchDeleteSupplierByIdsNormal(ids);
			if(se.getState() == SupplierStateEnum.DELETE.getState()) {
				modelMap.put("success", false);
				modelMap.put("code", 2);
				modelMap.put("msg", "希望强制删除吗?");
			}else if(se.getState() == SupplierStateEnum.SUCCESS.getState() ) {
				modelMap.put("success", true);
			}else {
				modelMap.put("success", false);
				modelMap.put("msg", "删除供应商信息失败");
			}
		}else if("2".equals(deleteType)) {
			//强制删除
			int effectedNum = supplierService.batchDeleteSupplierByIds(ids);
			if(effectedNum > 0) {
				modelMap.put("success", true);
			}else {
				modelMap.put("success", false);
				modelMap.put("msg", "删除供应商信息失败");
			}
		}else {
			modelMap.put("success", false);
			modelMap.put("msg", "删除操作被拒绝，请联系管理员");
		}		
		
		return modelMap;
	}
	
	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		int currentPage = HttpServletRequestUtil.getInt(request, "currentPage");
		int pageSize = HttpServletRequestUtil.getInt(request, "pageSize");
		String supplier = HttpServletRequestUtil.getString(request, "supplier");
		String type = HttpServletRequestUtil.getString(request, "type");
		String phoneNum = HttpServletRequestUtil.getString(request, "phonenum");
		String telephone = HttpServletRequestUtil.getString(request, "telephone");
		String description = HttpServletRequestUtil.getString(request, "description");
		
		SupplierExecution se =supplierService.getList(supplier, type, phoneNum, telephone, description, currentPage, pageSize);
		if(se.getState() == SupplierStateEnum.SUCCESS.getState()) {
			modelMap.put("success", true);
			modelMap.put("pages",se.getPages());//总页数
			modelMap.put("total", se.getTotal());//总数
			
			Map<String, Object> map = new HashMap<>();
			map.put("rows", se.getSupplierPageList());
			map.put("total", se.getTotal());
			//modelMap.put("userList", ue.getUserPageList());
			modelMap.put("supplierList", map);
		}else {
			modelMap.put("success", false);
			modelMap.put("msg", "查询列表失败");
		}
		
		return modelMap;
	}
	
	@RequestMapping(value = "/findBySelect_retail")
	@ResponseBody
	public JSONArray findBySelectRetail(HttpServletRequest request) {
		JSONArray arr = new JSONArray();
		SupplierExecution se =supplierService.findBySelectRetail();
		if(se.getState() == SupplierStateEnum.SUCCESS.getState()) {
			for (Supplier supplier : se.getSupplierList()) {
                JSONObject item = new JSONObject();
                item.put("id", supplier.getSupplierId());
                //客户名称
                item.put("supplier", supplier.getSupplier());
                item.put("advanceIn", supplier.getAdvanceIn()); //预付款金额
                arr.add(item);
            }
		}
		
		return arr;
	}
	
	/**
     * 查找客户信息-下拉框
     * @param request
     * @return
     */
	@RequestMapping(value = "/findBySelect_cus")
	@ResponseBody
	public JSONArray findBySelectCus(HttpServletRequest request) {
		JSONArray arr = new JSONArray();
		//获取前台传过来的值
		String ubType = HttpServletRequestUtil.getString(request, "UBType");
		String ubKeyId = HttpServletRequestUtil.getString(request, "UBKeyId");
		
		SupplierExecution se =supplierService.findBySelectCus();
		if(se.getState() == SupplierStateEnum.SUCCESS.getState()) {
			boolean customerFlag = systemConfigService.getCustomerFlag();
			for(Supplier supplier : se.getSupplierList()) {
				JSONObject item = new JSONObject();
				//勾选判断1
				boolean flag = false;
				try {
					UserBusinessExecution ue = userBusinessService.checkIsUserBusinessExist(ubType, ubKeyId, "[" + supplier.getSupplierId() + "]");
					if(ue.getState() == UserBusinessStateEnum.SUCCESS.getState()) {
						flag = true;
					}
				} catch (GlobalRuntimeException e) {
					e.printStackTrace();
				}
				if(!customerFlag || flag) {
					item.put("id", supplier.getSupplierId());
                    item.put("supplier", supplier.getSupplier()); //客户名称
                    arr.add(item);
				}
			}
		}
		
		return arr;
	}
	
	/**
     * 查找供应商信息-下拉框
     * @param request
     * @return
     */
	@RequestMapping(value = "/findBySelect_sup")
	@ResponseBody
	public JSONArray findBySelectSup(HttpServletRequest request){
		JSONArray arr = new JSONArray();
		SupplierExecution se =supplierService.findBySelectSup();
		if(se.getState() == SupplierStateEnum.SUCCESS.getState()) {
			for(Supplier supplier : se.getSupplierList()) {
				JSONObject item = new JSONObject();
                item.put("id", supplier.getSupplierId());
                //供应商名称
                item.put("supplier", supplier.getSupplier());
                arr.add(item);
			}
		}
		return arr;
	}
	
	@RequestMapping(value = "/add")
	@ResponseBody
	public Map<String, Object> add(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		String beanJson = HttpServletRequestUtil.getString(request, "info");
		SupplierExecution se = supplierService.insertSupplier(beanJson, request);
		if(se.getState() == SupplierStateEnum.SUCCESS.getState()) {
			modelMap.put("success", true);
		}else {
			modelMap.put("success", false);
		}
		
		return modelMap;
	}
	
	@RequestMapping(value = "/update")
	@ResponseBody
	public Map<String, Object> update(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		String beanJson = HttpServletRequestUtil.getString(request, "info");
		int supplierId = HttpServletRequestUtil.getInt(request, "id");
		SupplierExecution se = supplierService.updateSupplier(beanJson, supplierId, request);
		if(se.getState() == SupplierStateEnum.SUCCESS.getState()) {
			modelMap.put("success", true);
		}else {
			modelMap.put("success", false);
		}
		
		return modelMap;
	}
	
	@RequestMapping(value = "/checkIsNameExist")
	@ResponseBody
	public Map<String, Object> checkIsNameExist(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		int supplierId = HttpServletRequestUtil.getInt(request, "id");
		String supplier = HttpServletRequestUtil.getString(request, "name");
		
		//调用方法
		SupplierExecution se = supplierService.checkIsNameExist(supplierId, supplier);
		if(se.getState() == SupplierStateEnum.SUCCESS.getState()) {
			modelMap.put("success", true);//存在
		}else {
			modelMap.put("success", false);
		}
		
		return modelMap;
	}
	
	/**
	 * 用户对应客户显示
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/findUserCustomer")
	@ResponseBody
	public JSONArray findUserCustomer(HttpServletRequest request) {
		//获取前台传过来的值
		String type = HttpServletRequestUtil.getString(request, "UBType");
		String keyId = HttpServletRequestUtil.getString(request, "UBKeyId");
		JSONArray arr = new JSONArray();
		
		SupplierExecution se =supplierService.findUserCustomer();
		//开始拼接json数据
        JSONObject outer = new JSONObject();
        outer.put("id", 1);
        outer.put("text", "客户列表");
        outer.put("state", "open");
        //存放数据json数组
        JSONArray dataArray = new JSONArray();
        if(se.getState() == SupplierStateEnum.SUCCESS.getState()) {
        	for (Supplier supplier : se.getSupplierList()) {
                JSONObject item = new JSONObject();
                item.put("id", supplier.getSupplierId());
                item.put("text", supplier.getSupplier());
                //勾选判断1
                Boolean flag = false;
                UserBusinessExecution ue = userBusinessService.checkIsUserBusinessExist(type, keyId, "[" + supplier.getSupplierId() + "]");
                if(ue.getState() == UserBusinessStateEnum.SUCCESS.getState()) {
                	flag = true;
                }
                if (flag == true) {
                    item.put("checked", true);
                }
                //结束
                dataArray.add(item);
            }
        }
        outer.put("children", dataArray);
        arr.add(outer);
		return arr;
	}
}
